//
//  Chat.java
//  java-chat
//
//  Created by Joe Simpson on 26/08/2009.
//
// this file is JavaDoc compatable :D

// minimal references
// this is because you make everything else
import java.net.*;
import java.io.*;

/**
 * This class is for the main Chat item
 * it is universal so if you have a Java
 * application, you are free to use it
 * as long as you bind to the liscence
 */
// the code is under
public class Chat {
	/**
	 * this should be http://www.mashmaash.net for production
	 * for internal and non-releases it will say
	 * http://localhost/mashmash
	 */
	private String serverUrl = "http://localhost/mashmash/";
	private String newline = System.getProperty("line.separator");
	private SocketPermission permission = new SocketPermission("*:1024-", "connect,resolve");
	/**
	 * This will be changed to mashmash.net for production
	 * localhost is for testing
	 */
	private SocketPermission serverPermission = new SocketPermission("localhost:80", "connect,resolve");
	
	/**
	 * We are going to auth the user to use the app
	 * @return	String of either blank or a url to go to
	 */
	public String authUser(String appkey){
		String out = post(serverUrl + "api/gettoken.php", "appkey=" + appkey);
		System.out.println(out);
		return "moo";
	}
	/**
	 * Internal method to deal with Java's fussy way of POST-ing
	 * @return	The repsonse from POST-ing
	 */
	private String post(String url, String post){
		try{
			URL gourl = new URL(url);
			URLConnection connection = gourl.openConnection();
			connection.setDoOutput(true);
			OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream());
			out.write(post);
			out.close();
			BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
			String decodedString;
			String outputString = "";
			while ((decodedString = in.readLine()) != null) {
				outputString += decodedString + newline;
			}
			in.close();
			return outputString;
		}
		catch(Exception ex) {
			System.err.println("Error posting... sorry, I failed" + newline + "error details should follow bellow");
			System.err.println(ex.toString());
			return "";
		}
	}
}
